package dao;

import java.sql.*;

public class BaseDao {
    String driver = "com.mysql.cj.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/book?serverTimezone=GMT-8&characterEncoding=utf-8";
    String username = "root";
    String password = "root";

    /**
     * 获取连接
     *
     * @return
     */
    public Connection getConnection() {
        Connection conn = null;
        try {
            //1.加载驱动
            Class.forName(driver);
            //2.创建连接
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭资源
     */
    public void closeAll(ResultSet rs, PreparedStatement ps, Connection conn) {
        //8.释放资源，关闭连接
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public int eneuy(String sql, Object... objects) {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        int count = 0;
        try {
            ps = conn.prepareStatement(sql);
            if (objects != null) {
                for (int i = 0; i < objects.length; i++) {
                    ps.setObject(i + 1, objects[i]);
                }
            }
            count = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(null, ps, conn);
        }
        return count;
    }

    public ResultSet exeqy(String sql, Object... objects) {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        ResultSet re = null;
        try {
            ps = conn.prepareStatement(sql);
            if (objects != null) {
                for (int i = 0; i < objects.length; i++) {
                    ps.setObject(i + 1, objects[i]);
                }
            }
            re = ps.executeQuery();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return re;
    }
}
